package com.mephi.oshs.view.impl;

import com.mephi.oshs.view.api.IView;
import com.mephi.oshs.view.api.IViewManager;
import com.mephi.oshs.view.api.ViewId;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ViewManager implements IViewManager {

    private static final ViewManager singleton = new ViewManager();

    private final Map<ViewId, IView> viewMap = new HashMap<ViewId, IView>();

    public static ViewManager getInstance() {
        return singleton;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<IView> getAllViews() {
        return new ArrayList<IView>(this.viewMap.values());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void registerView(final IView view) {
        if (view == null) {
            throw new NullPointerException("registerView(): View can't be null.");
        }

        this.viewMap.put(view.getViewID(), view);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void unRegisterView(final IView view) {
        if (view == null) {
            throw new NullPointerException("unRegisterView(): View can't be null.");
        }
        if (this.viewMap.containsKey(view.getViewID())) {
            this.viewMap.remove(view.getViewID());
        } else {
            throw new IllegalArgumentException("unRegisterView(): View wasn't register before: " + view);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IView getViewById(final ViewId viewId) {
        if (this.viewMap.containsKey(viewId)) {
            return this.viewMap.get(viewId);
        }
        throw new IllegalArgumentException("getViewById(): View id wasn't register before: " + viewId);
    }
}